<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form ref="addformRef" :model="addForm" label-position="top">
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="changeBefore"
          @tab-click="clickTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cascaderList"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item1.attr_name"
              v-for="(item1, index) in manyList"
              :key="index"
            >
              <el-checkbox-group v-model="item1.attr_vals">
                <el-checkbox
                  :label="item2"
                  v-for="(item2, index1) in item1.attr_vals"
                  :key="index1"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyList"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="RequestHeard"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>

            <el-dialog
              title="预览图片"
              :visible.sync="dialogVisible"
              width="50%"
            >
              <img :src="filepath" alt="" />
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              ref="myQuillEditor"
              v-model="addForm.goods_introduce"
            />
            <el-button type="primary" class="index" @click="addgood"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      content: "",
      dialogVisible: false,
      filepath: "",
      RequestHeard: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      fileList: [],
      activeIndex: "0",
      cascaderList: [],
      addForm: {
        goods_name: "",
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        attrs: [],
        pics: [],
        goods_introduce: "",
      },
      manyList: [],
      onlyList: [],
      props: {
        label: "cat_name",
        children: "children",
        value: "cat_id",
        expandTrigger: "hover",
      },
    };
  },
  created() {
    this.getCategories();
  },
  methods: {
    //获取级联菜单数据
    async getCategories() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        this.$message.error("获取级联菜单数据失败");
      } else {
        this.cascaderList = res.data;
        // console.log(res);
      }
    },

    //切换级联菜单
    handleChange(newValue) {
      console.log(newValue);
      if (newValue.length !== 3) {
        this.addForm.goods_cat = [];
        this.$message.warning("只能选择第三级分类");
      }
    },

    //切换标签页之前
    changeBefore(activeName, oldActiveName) {
      console.log(activeName, oldActiveName);
      if (oldActiveName == "0" && this.addForm.goods_cat.length == 0) {
        this.$message.warning("请先选择商品分类");
        return false;
      }
    },

    //点击标签页
    clickTab(newVal) {
      if (this.activeIndex == "1" || this.activeIndex == "2") {
        this.getTab();
      }
    },

    //获取标签页内的数据
    async getTab() {
      var goods_sel;
      if (this.activeIndex == "1") {
        goods_sel = "many";
      } else if (this.activeIndex == "2") {
        goods_sel = "only";
      }
      const { data: res } = await this.$http.get(
        "categories/" + this.addForm.goods_cat[2] + "/attributes",
        {
          params: {
            sel: goods_sel,
          },
        }
      );
      if (goods_sel == "many") {
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyList = res.data;
      } else {
        this.onlyList = res.data;
      }
      console.log(res.data);
    },

    //点击图片预览大图
    handlePreview(file) {
      this.filepath = file.response.data.url;
      this.dialogVisible = true;

      console.log(file);
    },

    //点击删除图片
    handleRemove(res) {
      const path = res.response.data.tmp_path;
      const index = this.addForm.pics.findIndex((item) => {
        return item.pic == path;
      });

      this.addForm.pics.splice(index, 1);
      console.log(this.addForm.pics);
    },

    //文件上传成功
    handleSuccess(res) {
      const newPath = {
        pic: res.data.tmp_path,
      };

      this.addForm.pics.push(newPath);
      console.log(this.addForm.pics);
    },

    //点击添加商品
   async addgood() {
      const form = _.cloneDeep(this.addForm);
      form.goods_cat = form.goods_cat.join(",");
      this.manyList.forEach((item) => {
        const Info = {
          attr_id: item.attr_id,
          attr_value:item.attr_vals.join(' '),
        };
        form.attrs.push(Info)
      });
      this.onlyList.forEach((item) => {
        const Info = {
          attr_id: item.attr_id,
          attr_value:item.attr_vals,
        };
        form.attrs.push(Info)
      });
      console.log(form);
     const {data:res} = await this.$http.post('goods',form)
     if(res.meta.status !== 201){
        this.$message.error('添加商品失败')
     }else{
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
     }
    },
  },
};
</script>

<style scoped>
.el-steps {
  margin: 20px;
}

.el-input {
  width: 80%;
}

.el-step__title {
  font-size: 12px !important;
}

.el-card {
  min-height: 600px;
}

img {
  width: 100%;
  max-height: 400px;
}

.index.el-button {
  margin-top: 20px;
}
</style>
